﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using LeoGemini.Service.Infrastructure.Handler.Exception;
using Volo.Abp.Domain.Entities;

namespace GiftWishService.Domain.Aggregate.GiftCart
{
    /// <summary>
    /// 礼品袋聚合根
    /// </summary>
    [Table("tb_gift_cart")]
    public class GiftCart : AggregateRoot<Guid>
    {
        /// <summary>
        /// ORM框架使用
        /// </summary>
        protected GiftCart()
        {
            
        }

        public GiftCart(Guid id)
        {
            Id = id;
            Items = new List<GiftItem>();
        }

        public GiftCart(Guid id, Guid referenceUserId) : this(id)
        {
            ReferenceUserId = referenceUserId;
        }
        
        /// <summary>
        /// 所属用户id
        /// </summary>
        [Column("reference_user_id")]
        public virtual Guid ReferenceUserId { get; private set; }
        
        /// <summary>
        /// 礼品袋条目
        /// </summary>
        [Column("items")]
        public virtual ICollection<GiftItem> Items { get; private set; }

        /// <summary>
        /// 总价
        /// </summary>
        public virtual decimal TotalPrice
        {
            get
            {
                decimal totalPrice = 0;
                
                foreach (var gift in Items)
                {
                    totalPrice += gift.Price * gift.Num;
                }

                return totalPrice;
            }
        }

        /// <summary>
        /// 添加礼品
        /// </summary>
        public void AddGiftItem(string goodsId, Guid skuId, decimal price)
        {
            // 条目已存在
            if (Items.Any(item => item.GoodsId == goodsId && item.SkuId == skuId))
                throw new ConflictException(ErrorMessage.CART_ITEM_ALREADY_EXISTS);
            
            Items.Add(new GiftItem
            {
                GoodsId = goodsId,
                SkuId = skuId,
                Num = 1,
                Price = price
            });
        }

        /// <summary>
        /// 移除礼品
        /// </summary>
        public void RemoveGiftItem(string goodsId, Guid skuId)
        {
            var item = Items.First(g => g.GoodsId == goodsId && g.SkuId == skuId);
            
            // 条目不存在
            if (item == null)
                throw new NotFoundException(ErrorMessage.CART_ITEM_NOT_EXISTS);

            Items.Remove(item);
        }

        /// <summary>
        /// 获取礼品袋条目
        /// </summary>
        public GiftItem GetGiftItem(string goodsId, Guid skuId)
        {
            var item = Items.First(g => g.GoodsId == goodsId && g.SkuId == skuId);
            
            // 条目不存在
            if (item == null)
                throw new NotFoundException(ErrorMessage.CART_ITEM_NOT_EXISTS);

            return item;
        }
    }
}